<template>
  <div class="chat" @mousedown="startDrag" @touchstart.passive="startDrag" :style="{
    transform: `translate(${position.x}px, ${position.y}px)`,
    transition: isDragging ? 'none' : 'transform 0.3s ease',
    cursor: isDragging ? 'grabbing' : 'grab'
  }">
    <div class="header">
      <span>聊天列表</span>
      <button @click="closeChat">×</button>
    </div>
    <div class="list">
      <div v-for="item in chatList" :key="item.targetId" class="list-item" @click="selectUser(item)">
        <div class="avatar">
          <img :src="item.avatar ? `${BASE_URL}/api/staticfiles/avatar/${item.avatar}` : avatarIcon">
        </div>
        <div class="content">
          <div class="name">{{ item.targetName }}</div>
          <div class="last-message">{{ item.lastMessage.content }}</div>
        </div>
        <div class="time">{{ formatDate(item.lastMessage.createTime) }}</div>


      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import dayjs from 'dayjs';
import { useUserStore } from '/@/store';
import detail from '../detail.vue';
import AvatarIcon from '/@/assets/images/avatar.jpg';
import { BASE_URL } from "/@/store/constants";


const avatarIcon = AvatarIcon;

// 响应式状态
const position = ref({ x: 0, y: 0 })
const isDragging = ref(false)
const startOffset = ref({ x: 0, y: 0 })
const containerSize = ref({ width: 420, height: 600 })

// 初始化位置（居中显示）
onMounted(() => {
  position.value = {
    x: window.innerWidth / 2 - containerSize.value.width / 2,
    y: window.innerHeight / 2 - containerSize.value.height / 2
  }
})

// 拖动逻辑
const startDrag = (e) => {
  isDragging.value = true
  const clientX = e.clientX || e.touches[0].clientX
  const clientY = e.clientY || e.touches[0].clientY

  startOffset.value = {
    x: clientX - position.value.x,
    y: clientY - position.value.y
  }

  // 添加事件监听（使用 passive 提升性能）
  window.addEventListener('mousemove', handleDrag, { passive: true })
  window.addEventListener('touchmove', handleDrag, { passive: true })
  window.addEventListener('mouseup', stopDrag)
  window.addEventListener('touchend', stopDrag)
}

const handleDrag = (e) => {
  if (!isDragging.value) return

  const clientX = e.clientX || e.touches[0].clientX
  const clientY = e.clientY || e.touches[0].clientY

  // 计算边界限制
  const maxX = window.innerWidth - containerSize.value.width
  const maxY = window.innerHeight - containerSize.value.height

  position.value.x = Math.min(maxX, Math.max(0, clientX - startOffset.value.x))
  position.value.y = Math.min(maxY, Math.max(0, clientY - startOffset.value.y))
}

const stopDrag = () => {
  isDragging.value = false
  window.removeEventListener('mousemove', handleDrag)
  window.removeEventListener('touchmove', handleDrag)
}

// 窗口大小变化时重置位置
const handleResize = () => {
  position.value.x = Math.min(
    window.innerWidth - containerSize.value.width,
    position.value.x
  )
  position.value.y = Math.min(
    window.innerHeight - containerSize.value.height,
    position.value.y
  )
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
})



const router = useRouter();
const chatList = ref<ChatListItem[]>([]);

interface ChatListItem {
  targetId: string;
  targetName: string;
  avatar?: string;
  lastMessage: {
    content: string;
    createTime: string;
  };

}


// 获取当前用户ID（从Pinia）
const userStore = useUserStore();
const currentUserId = computed<string>(() => userStore.user_id);

// 加载聊天列表
const loadChatList = async () => {
  const res = await axios.get('http://localhost:8080/api/messages/chat-list', {
    params: { userId: currentUserId.value }
  });
  chatList.value = res.data;


};



// 跳转到聊天窗口
// const toChatBox = (targetUserId: string) => {
//   router.push({
//     name: 'ChatBox',
//     params: { targetUserId },
//     query: { userId: currentUserId.value }
//   });
// };
const selectUser = (item: ChatListItem) => {
  emit('select-user', {
    id: item.targetId,  // 将targetId映射为id
    name: item.targetName // 将targetName映射为name
  });
};


const props = defineProps({
  show: {
    type: Boolean,
    default: false
  }
});
const emit = defineEmits(['close', 'select-user']);
// 关闭弹窗
const closeChat = () => {
  emit('close');
};

// 时间格式化
const formatDate = (timestamp: string) => {
  return dayjs(timestamp).format('MM/DD HH:mm');
};

onMounted(() => {
  loadChatList();
});
</script>

<style scoped lang="less">
.chat {
  width: 420px;
  height: 600px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  transition: transform 0.3s ease;
  top: 0;
  left: 500px;

  /* 新增拖动相关样式 */
  user-select: none;
  touch-action: none;
  position: fixed;
  z-index: 1000;
  will-change: transform;
  /* 优化动画性能 */

  /* 拖动时的视觉反馈 */
  transition: transform 0.3s ease, box-shadow 0.3s ease;

  &:hover {
    transform: translateY(-2px);
  }

  &:active {
    box-shadow: 0 12px 32px rgba(0, 0, 0, 0.2);
  }
}

.header {
  padding: 20px;
  background: linear-gradient(135deg, #409eff, #66b1ff);
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: relative;
  font-size: 18px;

  button {
    width: 32px;
    height: 32px;
    border: none;
    background: rgba(255, 255, 255, 0.15);
    border-radius: 50%;
    color: white;
    font-size: 24px;
    cursor: pointer;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

    &:hover {
      background: rgba(255, 255, 255, 0.25);
      transform: rotate(90deg) scale(1.1);
    }

    &:active {
      transform: rotate(90deg) scale(0.9);
    }
  }
}

.list {
  flex: 1;
  overflow-y: auto;
  padding: 12px 0;
  background: #f8f9fa;
}

.list-item {
  display: grid;
  grid-template-columns: 56px 1fr auto;
  gap: 16px;
  align-items: center;
  padding: 16px 20px;
  margin: 0 12px;
  border-radius: 12px;
  background: white;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  transition: all 0.25s ease;
  cursor: pointer;

  &:not(:last-child) {
    margin-bottom: 8px;
  }

  &:hover {
    transform: translateX(4px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  &:active {
    transform: translateX(2px);
  }
}

.avatar {
  width: 56px;
  height: 56px;
  border-radius: 50%;
  overflow: hidden; // 确保图片圆形裁剪
  position: relative;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

  img {
    width: 100%;
    height: 100%;
    object-fit: cover; // 保持图片比例
    transition: transform 0.3s ease;
  }

  // 悬停效果
  &:hover {
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);

    img {
      transform: scale(1.05);
    }
  }

  // 点击效果
  &:active {
    transform: scale(0.95);
  }



}

.content {
  min-width: 0;

  .name {
    font-size: 16px;
    font-weight: 600;
    color: #1a1a1a;
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .last-message {
    font-size: 14px;
    color: #666;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.time {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
  padding-left: 16px;
}

@media (max-width: 768px) {
  .chat {
    width: 100vw;
    height: 100vh;
    border-radius: 0;
    box-shadow: none;
  }

  .list-item {
    margin: 0 8px;
    padding: 12px;
    grid-template-columns: 48px 1fr auto;
    gap: 12px;
  }

  .avatar {
    width: 48px;
    height: 48px;
    font-size: 20px;
  }
}

.unread-badge {
  position: absolute;
  top: -8px;
  right: -8px;
  background: red;
  color: white;
  border-radius: 50%;
  padding: 4px 8px;
  font-size: 12px;
}

.unread-dot {
  background: red;
  color: white;
  border-radius: 50%;
  padding: 2px 6px;
  margin-left: 4px;
}
</style>